<!-- 环境检测 -->
<template>
  <div>
    <div v-if="!showSpcDetail" class="page-main">
      <div class="header_box">
        <div class="top_box">
          <timeItem />
          <weatherItem :dataList="weatherData" />
          <div>
            <div class="right_btn">
              <px-button class="btn_item" type="primary" plain @click="viewSpcDetail">查看历史</px-button>
            </div>
            <div class="right_btn">
              <px-popover :visible="visibleY2" placement="left-start" title="设置环比周期" :width="290">
                <px-form :inline="true" :model="weatherForm">
                  <px-row>
                    <px-col :span="12">
                      <px-form-item label="" prop="num" style="width: 120px">
                        <px-input v-model="weatherForm.num" placeholder="请输入" clearable />
                      </px-form-item>
                    </px-col>
                    <px-col :span="12">
                      <px-form-item label="" prop="type" style="width: 120px">
                        <px-select v-model="weatherForm.type" filterable placeholder="请选择">
                          <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
                        </px-select>
                      </px-form-item>
                    </px-col>
                  </px-row>
                </px-form>
                <div style="margin: 0; text-align: right">
                  <px-button size="small" text @click="visibleY2 = false">取消</px-button>
                  <px-button size="small" type="primary" @click="editSpcY2">确定</px-button>
                </div>
                <template #reference>
                  <px-button type="primary" text @click="visibleY2 = true">设置环比周期</px-button>
                </template>
              </px-popover>
            </div>
          </div>
        </div>
        <div class="switch_box">
          <px-scrollbar>
            <div class="switch_tabs">
              <div v-for="(item, index) in areaData" :key="index" class="switch_item">
                <div class="item_name">{{ item.name }}</div>
                <div :class="[item.worningNum > 0 ? 'item_red' : 'item_green']">{{ item.worningNum }}</div>
              </div>
            </div>
          </px-scrollbar>
        </div>
        <div class="tabs">
          <CustomTabs :tabList="tabsOption" :activeName="activeName" @tabSelect="tabSelectHandler" />
        </div>
      </div>
      <div ref="switchTabsContentRef">
        <px-scrollbar class="con_bar">
          <transition name="fab-tabs-fade" mode="out-in">
            <component :is="activeCom" :activeName="activeName" :areaList="areaData" />
          </transition>
        </px-scrollbar>
      </div>
    </div>
    <div v-if="showSpcDetail" class="spc_detail">
      <div class="top_turnback">
        <px-button type="primary" :icon="ArrowLeft" @click="turnBack">返回</px-button>
      </div>
      <div class="import-bottle-title">
        <px-icon color="#F59E0B"><WarningFilled /></px-icon>
        &nbsp;指标曲线请先设置SPC
        <span class="download" @click="gotoSpc"> 去设置 </span>
      </div>
      <px-form ref="querySpcDetailRef" :model="querySpcDetailParams" :inline="true" label-width="68px">
        <px-form-item label="指标类型" prop="alarmLevel">
          <px-checkbox-group v-model="spcJobList">
            <px-checkbox v-for="item in weatherSpcJobList" :key="item.id" :label="item.itemDesc">{{ item.itemName }}</px-checkbox>
            <!-- <px-checkbox label="weather.outdoor.temp.dry_1">室外干球温度</px-checkbox>
            <px-checkbox label="weather.outdoor.temp.wet_1">室外湿球温度</px-checkbox>
            <px-checkbox label="weather.outdoor.euthalpy_1">焓值</px-checkbox>
            <px-checkbox label="weather.outdoor.humidity_1">绝对湿度</px-checkbox>
            <px-checkbox label="weather.outdoor.temp.dew_1">露点</px-checkbox> -->
          </px-checkbox-group>
        </px-form-item>
        <px-form-item label="时间日期" style="width: 460px">
          <px-date-picker
            v-model="dateRangeSpcDetail"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </px-form-item>
        <px-form-item>
          <px-button type="primary" @click="querySpc">查询</px-button>
          <px-button @click="resetSpc">重置</px-button>
        </px-form-item>
      </px-form>
      <div class="con_spc">
        <div class="spc_com">
          <lineChart ref="spcChartWeatherRef" :key="new Date().getTime()" :width="800" :options="weatherOptions" />
        </div>
      </div>
      <barTitle title="数据明细" />
      <px-table v-loading="loading" max-height="389" :header-cell-style="{ background: '#e7eefb', color: '#000' }" border :data="dataDetailTable">
        <px-table-column label="时间" prop="startTime" />
        <px-table-column label="大气指标类型" prop="indicatorName" />
        <px-table-column label="值" prop="avgValue" />
      </px-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import CustomTabs from "@/components/Tabs/index.vue";
import { ref, markRaw, computed, onMounted, onUnmounted, toRefs, reactive } from "vue";
import wenshidufengsuCom from "./wenshidufengsu/index.vue";
import particleCom from "./particle/index.vue";
import amcCom from "./AMC/index.vue";
import weatherItem from "../components/weatherItem/index.vue";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import timeItem from "../components/timeItem/index.vue";
import { type OptionsType } from "@/components/ReSegmented";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import lineChart from "../components/lineChart/index.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter } from "vue-router";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getPointNewValue,
  getPointsCurve,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  queryAreaWornings
} from "@/api/machineClass";

const state = reactive<any>({
  weatherForm: {
    num: "",
    type: "hour"
  },
  spcJobList: [],
  weatherSpcJobList: [],
  areaData: [],
  dataDetailTable: [],
  dateRangeSpcDetail: [],
  weatherOptions: {},
  querySpcDetailParams: {},
  weatherData: {}
});

const {
  weatherForm,
  areaData,
  weatherData,
  dataDetailTable,
  dateRangeSpcDetail,
  spcJobList,
  weatherSpcJobList,
  querySpcDetailParams,
  weatherOptions
} = toRefs(state);

const defaultHeight = ref<number>(700);

const router = useRouter();

const tabsOption = ref<Array<OptionsType>>([
  {
    name: "wenshidufengsu",
    label: "温湿度、风速",
    com: markRaw(wenshidufengsuCom)
  },
  {
    name: "Particle",
    label: "Particle",
    com: markRaw(particleCom)
  },
  {
    name: "AMC",
    label: "AMC",
    com: markRaw(amcCom)
  }
]);

const loading = ref(false);

const visibleY2 = ref(false);

const showSpcDetail = ref(false);

const activeName = ref("wenshidufengsu");

const typeList = [
  {
    value: "hour",
    label: "小时"
  },
  {
    value: "day",
    label: "日"
  }
];

const switchTabsContentRef = ref(null);

const activeCom = computed(() => tabsOption.value.find(item => item.name === activeName.value).com);
const switchTabsChangeHandler = async () => await useUpdateDomHeight(defaultHeight, switchTabsContentRef, null, defaultHeight.value);

const getWeatherData = async () => {
  const param = {
    diffHours: weatherForm.value.num || 0
  };
  const data = await queryWeatherData(param);
  weatherData.value = data;
};

// 获取区域列表
const queryAreaList = async (id: string) => {
  const data: any = await getFabZone();
  data.forEach((item: any) => {
    getWorningNum(item.code);
  });
  areaData.value = data;
};

// 根据区域获取报警信息
const getWorningNum = async (id: string) => {
  const params = {
    // areaId: id, // id 暂时写死联调
    // roomId: "ROOM_b20032", // id 暂时写死联调
    pageNum: 1,
    pageSize: 999
  };
  params[`${id.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = id.indexOf("ROOM") === -1 ? [id] : id;
  const res: any = await queryAreaWornings(params);
  areaData.value.map((item: any) => {
    if (item.code === id) {
      item.worningNum = res?.data.length;
    }
    return item;
  });
};

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let hour = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
  let minites = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${year}-${month}-${da}`, `${year}-${month}-${da}`]; // 近一年时间范围
  // return [`${year}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} ${hour}:${minites}:${seconds}`]; // 近一年时间范围
};

const viewSpcDetail = () => {
  showSpcDetail.value = true;
  dateRangeSpcDetail.value = initSpcDate();
  querySpc();
};

const turnBack = () => {
  showSpcDetail.value = false;
};

// 查询报警明细
const querySpc = async () => {
  // const cwData = await queryChildByTypeCodeAndItemValue({
  //   value: "CWConfig",
  //   typeCode: "MCTS"
  // });
  // spcDataList.value = cwData ? cwData : [];
  // const jobIDs = [];
  // spcDataList.value.forEach((item: any) => {
  //   jobIDs.push(JSON.parse(item.itemDesc).spc_job);
  // });
  const params = {
    jobIdList: [...spcJobList.value],
    timePeriod: "hour",
    startTime: dateRangeSpcDetail.value[0] + " 00:00:00",
    endTime: dateRangeSpcDetail.value[1] + " 23:59:59"
  };
  const res: any = await spcquerySpcAnalysis(params);
  // 需要展示的SPC 可替换下方jobIdS
  // const showSpcIds = [
  //   "weather.outdoor.temp.dry_1",
  //   "SPC_QA_CWConfig11",
  //   "SPC_QA_CWConfig12",
  //   "SPC_QA_CWConfig1",
  //   "SPC_QA_CWConfig2",
  //   "SPC_QA_CWConfig3",
  //   "SPC_QA_CWConfig4",
  //   "SPC_QA_CWConfig7",
  //   "SPC_QA_CWConfig8"
  // ];
  // 过滤
  // const arr = res.filter((item: any) => jobIDs.indexOf(item.jobId) !== -1 && item.pointValues && item.pointValues.length > 0); // 过滤出有数据的
  const arr = res.filter((item: any) => spcJobList.value.indexOf(item.jobId) !== -1); // 过滤出有数据的
  const spcList = arr.map((item: any) => {
    item.startTime = dateRangeSpcDetail.value[0];
    item.endTime = dateRangeSpcDetail.value[1];
    item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
    return {
      ...item
    };
  });
  dataDetailTable.value = spcList;
  const obj = spcList[0];
  // weatherOptions.value = obj;

  const yAxis =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        name: obj.indicatorName,
        nameLocation: "middle", //居中
        offset: (0 + index) * 50,
        nameGap: 70, //轴线距离
        nameRotate: 90, //字体选择角度
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        }
      };
    });
  const series =
    spcList &&
    spcList.map((obj, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: obj && obj.pointValues.length > 0 ? obj.pointValues.map(item => item.value) : [],
        type: "line",
        name: obj.indicatorName,
        yAxisIndex: ind,
        // areaStyle: {
        //   opacity: 0.15
        // },
        symbol: "none",
        markLine: {
          symbol: "none",
          data: [
            {
              name: "USL值",
              yAxis: Number(obj.uslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `USL值${obj.uslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            },
            {
              name: "UCL值",
              yAxis: Number(obj.uclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UCL值${obj.uclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "UWL值",
              yAxis: Number(obj.uwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UWL值${obj.uwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "Target值",
              yAxis: Number(obj.targetValue),
              lineStyle: {
                color: "#00E272",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `Target值${obj.targetValue}`,
                color: "#00E272",
                fontWeight: 600
              }
            },
            {
              name: "LWL值",
              yAxis: Number(obj.lwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LWL值${obj.lwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "LCL值",
              yAxis: Number(obj.lclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LCL值${obj.lclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "LSL值",
              yAxis: Number(obj.lslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `LSL值${obj.lslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            }
          ]
        }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    color: "#ccc",
    grid: {
      left: "60px",
      top: "40px",
      right: "100px",
      bottom: "5%",
      containLabel: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        obj && obj.pointValues.length > 0
          ? obj.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  weatherOptions.value = option;
};

// 重置筛选条件
const resetSpc = async () => {
  dateRangeSpcDetail.value = initSpcDate();
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  querySpc();
};

const gotoSpc = () => {
  router.push({ path: "/machine/spc/spcseetings" });
};

const editSpcY2 = () => {
  getWeatherData();
  visibleY2.value = false;
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const tabSelectHandler = async (selectName: string) => {
  activeName.value = selectName;
  await switchTabsChangeHandler();
};
onMounted(async () => {
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "OUTDOOR_WEATHER"
  });
  weatherSpcJobList.value = res;
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  getWeatherData();
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  await queryAreaList(id);
  await switchTabsChangeHandler();
});

onUnmounted(() => {
  useCancelUpdateDomHeight();
});
</script>

<style lang="scss" scoped>
.page-main {
  .header_box {
    display: flex;
    flex-flow: column;
    width: 100%;
    min-width: 1300px;
    padding: 16px 24px 0;
    background-color: white;
    border-radius: 4px;

    .top_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .right_btn {
        display: flex;
        align-items: center;
        justify-content: center;

        .btn_item {
          margin-bottom: 8px;
        }
      }
    }

    .switch_box {
      width: 100%;
      margin-top: 16px;

      .switch_tabs {
        display: flex;
        flex-flow: row nowrap;
        gap: 12px;
        align-items: center;
        justify-content: flex-start;

        .switch_item {
          min-width: 92px;
          font-size: 14px;
          text-align: center;
          border: 1px solid #dcdcdc;
          border-radius: 3px;
        }

        .item_name {
          padding: 0 7px;
          white-space: nowrap;
          border-radius: 3px 3px 0 0;
        }

        .item_red {
          color: #fff;
          background-color: #ef4444;
          border-radius: 0 0 2px 2px;
        }

        .item_green {
          color: #fff;
          background-color: #10b981;
          border-radius: 0 0 2px 2px;
        }
      }
    }
  }

  .con_bar {
    .fab-tabs-fade-enter-active,
    .fab-tabs-fade-leave-active {
      transition: all 0.4s ease;
    }

    .fab-tabs-fade-enter-from {
      opacity: 0;
      transform: translateX(-80px);
    }

    .fab-tabs-fade-leave-to {
      opacity: 0;
      transform: translateX(80px);
    }
  }
}

.spc_detail {
  width: 100%;
  min-width: 1300px;
  padding: 16px 24px;
  background-color: white;

  .con_spc {
    display: flex;
    justify-content: space-between;
    margin-top: 16px;

    .spc_com {
      position: relative;
      flex: 1;

      .edit_form {
        display: flex;
        flex-flow: row nowrap;
        gap: 10px;
      }

      .edit_y1 {
        position: absolute;
        cursor: pointer;
      }
    }
  }

  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin: 16px 0;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      margin-left: 8px;
      color: #3b82f6;
      cursor: pointer;
    }
  }
}
</style>
